import React, { Component } from "react";
import {
  Table,
  DatePicker,
  Input,
  message,
  Badge,
  Button,
  Form,
  Row,
  Col,
  Select,
  Modal
} from "antd";
import moment from "moment";
// import Icon from "@cbd/icon";
import { connect } from "dva";
import tableFilter from "../../../components/tableFilter";
// import ExportBtn from "../../../components/exportBtn";
import styles from "./index.less";
import api from "../../../services/publicApi";
import ToggleColumns from "../../../components/toggleColumns";

const { RangePicker } = DatePicker;

@connect(({ messageSend, channelDictionaryModel, user }) => ({
  messageSend,
  channelDictionaryModel,
  userData: user
}))
@Form.create()
@tableFilter
class MessagePage extends Component {
  constructor(props) {
    super(props);
    this.state = {
      selectedId: [],
      creTimeStart: "",
      creTimeEnd: "",
      sourceName: "",
      receiverName: "",
      pushChannelName: "",
      pageNum: 1,
      pageSize: 10,
      pushChannelType: "",
      ownerDept: "",
      pushResultCode: "",
      ascOrDesc: "desc",
      totalCount: 0,
      loading: false,
      exportLoading: false,
      picVisible: false,
      type: null,
      recieverUserVisible: false,
      listOfRrecieverUser: [],
      messageVisible: false,
      msgContent: "",
      logVisible: false,
      showColumns: [],
      columnCfg: {},
      userId: ""
    };
  }

  componentDidMount() {
    // const { dispatch } = this.props;
    this.getData();
    const { userId } = this.state;
    if (userId) {
      // 获取隐藏表格配置
      this.getColumnCfg(userId);
    }
  }

  componentDidUpdate(_, prevState) {
    const { userId } = this.state;
    if (userId && userId !== prevState.userId) {
      // 获取隐藏表格配置
      this.getColumnCfg(userId);
    }
  }

  static getDerivedStateFromProps(nextProps, prevState) {
    const { userInfo = {} } = nextProps.userData;
    if (userInfo.userId && userInfo.userId !== prevState.userId) {
      return { userId: userInfo.userId };
    }
    return null;
  }

  getColumnCfg = userId => {
    api.getColumnsByTable({ user: userId, tag: "msgSendCtrl" }).then(res => {
      if (res.success) {
        if (res.datas.length === 0 || res.datas[0].config === "") {
          this.setState({
            columnCfg: res.datas[0] || {},
            showColumns: this.getColumns()
          });
        } else {
          const hiddenArr = res.datas[0].config.split(",");
          this.setState({
            columnCfg: res.datas[0] || {},
            showColumns: this.getColumns().filter(
              c => !hiddenArr.find(hc => hc === c.dataIndex)
            )
          });
        }
      } else {
        message.error(res.errMsg);
      }
    });
  };

  onSetColumns = (shows, hiddens) => {
    const { userId, columnCfg } = this.state;
    this.setState({
      showColumns: shows
    });
    // 同步动态表格隐藏列信息
    api
      .updateColumnsByTable({
        config: hiddens.map(h => h.dataIndex).join(","),
        user: userId,
        tag: columnCfg.tag || "msgSendCtrl",
        id: columnCfg.id
      })
      .then(res => {
        if (!res.success) {
          message.warning("动态表格同步失败");
        }
      });
  };

  dateChange = (e = []) => {
    this.setState({
      creTimeStart: e.length ? e[0].format("YYYY-MM-DD 00:00:00") : undefined,
      creTimeEnd: e.length ? e[1].format("YYYY-MM-DD 23:59:59") : undefined,
      selectedId: []
    });
  };

  handleTableChange = (
    e,
    {
      pushChannelTypeName = [],
      ownerDeptName = [],
      pushResultCodeReturn = [],
      templateType = []
    },
    sorter
  ) => {
    const { current, pageSize } = e;
    const {
      ownerDept,
      pushChannelType,
      pushResultCode,
      selectedId,
      type
    } = this.state;
    const isFilter =
      (ownerDeptName[0] && ownerDeptName[0] !== ownerDept) ||
      (pushChannelTypeName[0] && pushChannelTypeName[0] !== pushChannelType) ||
      (pushResultCodeReturn[0] && pushResultCodeReturn[0] !== pushResultCode) ||
      (templateType[0] && templateType[0] !== type);
    this.setState(
      {
        pageNum: isFilter ? 1 : current,
        pageSize,
        ascOrDesc: sorter.order && sorter.order === "ascend" ? "asc" : "desc",
        ownerDept: ownerDeptName[0] || "",
        pushChannelType: pushChannelTypeName[0] || "",
        pushResultCode: pushResultCodeReturn[0] || "",
        selectedId: isFilter ? [] : selectedId,
        type: templateType[0] || null
      },
      () => {
        this.getData();
        // this.getDepData();
      }
    );
  };

  handleSearch = e => {
    this.setState(
      {
        sourceNameOrReceiverName: e,
        pageNum: 1,
        selectedId: []
      },
      () => {
        this.getData();
        // this.getDepData();
      }
    );
  };

  clearChange = e => {
    if (e.target.value !== "") return;
    this.setState(
      {
        sourceNameOrReceiverName: "",
        pageNum: 1,
        selectedId: []
      },
      () => {
        this.getData();
        // this.getDepData();
      }
    );
  };

  getTypeName = (value = 0) => {
    const {
      messageSend: { stateFilter }
    } = this.props;
    const temp = stateFilter.find(k => Number(k.value) === value);
    return temp ? temp.text : "";
  };

  renderState = text => {
    if (text === "成功") {
      return <Badge status="success" text="成功" />;
    }

    return <Badge status="default" text="失败" />;
  };

  getColumns = () => {
    const { pageNum, pageSize } = this.state;
    return [
      {
        title: "序号",
        dataIndex: "id",
        width: 50,
        render: (a, b, c) => <span>{pageSize * (pageNum - 1) + c + 1}</span>
      },
      {
        title: "租户编码",
        dataIndex: "tenantCode",
        ellipsis: true
      },
      {
        title: "租户名称",
        dataIndex: "tenantName",
        ellipsis: true
      },
      {
        title: "消息任务ID",
        dataIndex: "msgId",
        ellipsis: true
      },
      {
        title: "接收渠道类型",
        width: 100,
        dataIndex: "pushChannelTypeName",
        ellipsis: true
      },
      {
        title: "渠道账户编码",
        width: 100,
        dataIndex: "pushChannelCode",
        ellipsis: true
      },
      {
        title: "渠道账户名称",
        width: 100,
        dataIndex: "pushChannelName",
        ellipsis: true
      },
      // {
      //   title: "消息业务类型",
      //   width: 100,
      //   dataIndex: "ywType"
      // },
      {
        title: "消息模版编码",
        width: 100,
        dataIndex: "templateCode",
        ellipsis: true
      },
      {
        title: "消息模版名称",
        width: 100,
        dataIndex: "templateName",
        ellipsis: true
      },
      {
        title: "场景编码",
        dataIndex: "sceneCode",
        ellipsis: true
      },
      {
        title: "场景名称",
        dataIndex: "sceneName",
        ellipsis: true
      },
      {
        title: "发送时间",
        width: 150,
        dataIndex: "createTime",
        ellipsis: true
      },
      {
        title: "发送状态",
        dataIndex: "status",
        render: text => this.renderState(text)
      },
      {
        title: "接收人列表",
        dataIndex: "receiverDTOList",
        width: 80,
        fixed: "right",
        align: "center",
        render: text => <a onClick={() => this.onReciveUserLook(text)}>查看</a>
      },
      {
        title: "消息内容",
        dataIndex: "content",
        width: 80,
        fixed: "right",
        align: "center",
        render: text => <a onClick={() => this.onMessageLook(text)}>查看</a>
      },
      // {
      //   title: "发送日志",
      //   dataIndex: "sendLog",
      //   width: 80,
      //   fixed: "right",
      //   align: "center",
      //   render: () => <a onClick={() => this.onLogLook()}>查看</a>
      // },
      {
        title: "操作",
        dataIndex: "sendAct",
        width: 80,
        fixed: "right",
        align: "center",
        render: (text, record) => {
          if (record.status === "成功") {
            return null;
          }
          return (
            <a onClick={() => this.onFailResend(record.msgId)}>发送重试</a>
          );
        }
      }
    ];
  };

  // 获取展示数据、查询、过滤、排序

  getData = () => {
    const { dispatch, form } = this.props;
    const { pageNum, pageSize } = this.state;
    this.setState({
      loading: true
    });
    const { getFieldsValue } = form;
    const { sendDate, ...rest } = getFieldsValue();
    const params = {
      ...rest,
      pageNum,
      pageSize,
      startDate: sendDate ? moment(sendDate[0]) : "",
      endDate: sendDate ? moment(sendDate[1]) : ""
    };
    // const params = {
    //   creTimeStart,
    //   creTimeEnd,
    //   sourceName,
    //   receiverName,
    //   pushChannelName,
    //   pushChannelType,
    //   ownerDept,
    //   pushResultCode,
    //   ascOrDesc,
    //   pageNum,
    //   pageSize,
    //   handleLogIds: null,
    //   templateType: type
    // };
    dispatch({
      type: "messageSend/fetchMessageList",
      payload: { ...params }
    }).then(totalCount => {
      this.setState({
        totalCount,
        loading: false
      });
    });
  };

  // 导出excel
  exportExcel = type => {
    const { dispatch, messageSend: { messageList = [] } = {} } = this.props;
    const {
      selectedId,
      sourceNameOrReceiverName,
      ascOrDesc,
      pushChannelType,
      ownerDept,
      pushResultCode,
      creTimeStart,
      creTimeEnd,
      sourceName,
      pushChannelName,
      receiverName
    } = this.state;
    if (messageList.length <= 0) {
      message.error("当前没有导出内容", 1);
      return;
    }
    if (type !== "all" && selectedId.length <= 0) {
      message.error("请选择需要导出的内容", 1);
      return;
    }
    this.setState({
      exportLoading: true
    });
    const payload = {
      // creTimeStart,
      // creTimeEnd,
      sourceNameOrReceiverName,
      // ascOrDesc,
      // pushChannelType,
      // ownerDept,
      // pushResultCode,
      pageNum: 1,
      pageSize: 10000,
      handleLogIds: type === "all" ? [] : selectedId,
      sourceName,
      pushChannelName,
      receiverName,
      creTimeEnd,
      creTimeStart,
      pushResultCode,
      ownerDept,
      pushChannelType,
      ascOrDesc
    };
    dispatch({
      type: "messageSend/exportExcel",
      payload
    }).then(() => {
      this.setState({
        exportLoading: false
      });
    });
  };

  handleDisabledDate = current => current < moment().subtract(6, "months");

  setPicVisible = () => {
    const { picVisible } = this.state;
    this.setState({
      picVisible: !picVisible
    });
  };

  changeSourceName = e => {
    this.setState({
      sourceName: e.target.value
    });
  };

  changeReceiverName = e => {
    this.setState({
      receiverName: e.target.value
    });
  };

  changePushChannelName = e => {
    this.setState({
      pushChannelName: e.target.value
    });
  };

  clearNames = () => {
    this.setState({
      sourceName: "",
      receiverName: "",
      pushChannelName: "",
      creTimeStart: "",
      creTimeEnd: ""
    });
  };

  query = () => {
    this.setState(
      {
        pageNum: 1
      },
      () => {
        this.getData();
        // this.getDepData();
      }
    );
  };

  handleSubmit() {
    // const { form } = this.props;
    // const { validateFields } = form;
    // validateFields((err, fieldsValue) => {
    //   window.console.log(err);
    //   window.console.log(fieldsValue);
    // });
    this.query();
    return false;
  }

  onReset() {
    const { form } = this.props;
    form.resetFields();
    this.query();
  }

  onReciveUserLook(listOfRecieverUser) {
    if (listOfRecieverUser && listOfRecieverUser.length > 0) {
      this.setState({ recieverUserVisible: true, listOfRecieverUser });
      return;
    }
    message.warning("接收人列表为空");
  }

  onMessageLook(text) {
    let content = "";
    const textArr = text ? JSON.parse(text) : [];
    textArr.forEach(element => {
      content += element.content;
    });
    this.setState({ messageVisible: true, msgContent: content });
  }

  onLogLook() {
    this.setState({ logVisible: true });
  }

  onFailResend(msgId) {
    const { dispatch } = this.props;
    if (msgId) {
      dispatch({
        type: "messageSend/msgRePush",
        payload: { msgId }
      }).then(res => {
        window.console.log(res);
        if (res && res.errCode === 0) {
          message.success("操作成功");
          this.getData();
        } else {
          message.error(res.errMsg);
        }
        // this.setState({
        //   totalCount,
        //   loading: false
        // });
      });
    }
  }

  render() {
    const {
      messageSend: {
        messageList = []
        // stateFilter = [],
        // channelDepFilter = []
      },
      channelDictionaryModel: { channelsTypesData = [] },
      // getColumnSearchProps = () => {},
      form
    } = this.props;
    const { getFieldDecorator } = form;
    const {
      loading,
      pageNum,
      totalCount,
      // selectedId,
      listOfRecieverUser,
      msgContent,
      showColumns
    } = this.state;
    // const rowSelection = {
    //   selectedRowKeys: selectedId,
    //   onChange: selectedRowKeys => {
    //     this.setState({
    //       selectedId: selectedRowKeys
    //     });
    //   }
    // };

    const userColumn = [
      {
        title: "用户id",
        dataIndex: "userId"
      },
      {
        title: "用户名称",
        dataIndex: "userName"
      },
      {
        title: "发送状态",
        dataIndex: "status",
        render: text => this.renderState(text)
      },
      {
        title: "结果描述",
        dataIndex: "pushResultDescription"
      },
      {
        title: "发送时间",
        dataIndex: "createTime"
      }
    ];
    const formItemLayout = {
      labelCol: {
        xs: { span: 24 },
        sm: { span: 8 }
      },
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 16 }
      }
    };
    return (
      <div className={styles.root}>
        <div className={styles.titleBox}>消息分发</div>
        <div
          style={{
            margin: "16px 0",
            padding: "0 24px"
          }}
        >
          <div
            style={{
              fontSize: 14,
              color: "rgba(0,0,0,0.85)",
              marginBottom: 16,
              display: "flex",
              alignItems: "center",
              padding: "14px 16px",
              background: "#fff"
            }}
          >
            <Form
              {...formItemLayout}
              onSubmit={() => this.handleSubmit()}
              style={{ width: "100%" }}
            >
              <Row>
                <Col span={6}>
                  <Form.Item label="消息任务ID">
                    {getFieldDecorator("msgId")(
                      <Input placeholder="请输入消息任务ID" />
                    )}
                  </Form.Item>
                </Col>
                <Col span={6}>
                  <Form.Item
                    label="接收渠道类型"
                    labelCol={{ span: 10 }}
                    wrapperCol={{ span: 14 }}
                  >
                    {getFieldDecorator("pushChannelType")(
                      <Select placeholder="请选择" allowClear>
                        {channelsTypesData.map(d => (
                          <Select.Option key={d.value} value={d.value}>
                            {d.des}
                          </Select.Option>
                        ))}
                      </Select>
                    )}
                  </Form.Item>
                </Col>
                <Col span={6}>
                  <Form.Item label="渠道账号">
                    {getFieldDecorator("pushChannel")(
                      <Input placeholder="请输入渠道账号编码或名称" />
                    )}
                  </Form.Item>
                </Col>
                <Col span={6}>
                  <Form.Item label="场景">
                    {getFieldDecorator("scene")(
                      <Input placeholder="请输入场景编码或名称" />
                    )}
                  </Form.Item>
                </Col>
              </Row>
              <Row>
                <Col span={6}>
                  <Form.Item label="消息模版">
                    {getFieldDecorator("template")(
                      <Input placeholder="请输入消息模版编码或名称" />
                    )}
                  </Form.Item>
                </Col>
                <Col span={6}>
                  <Form.Item label="发送时间">
                    {getFieldDecorator("sendDate")(<RangePicker />)}
                  </Form.Item>
                </Col>
                <Col span={6}>
                  <Form.Item label="发送状态">
                    {getFieldDecorator("status")(
                      <Select placeholder="请选择" allowClear>
                        <Select.Option value={true}>成功</Select.Option>
                        <Select.Option value={false}>失败</Select.Option>
                      </Select>
                    )}
                  </Form.Item>
                </Col>
                <Col span={6}>
                  <Form.Item label="消息源">
                    {getFieldDecorator("msgSource")(
                      <Input placeholder="请输入消息源编码或名称" />
                    )}
                  </Form.Item>
                </Col>
              </Row>
              <Row>
                <Col span={12}></Col>
                <Col span={12} style={{ textAlign: "right" }}>
                  <ToggleColumns
                    originColumns={this.getColumns()}
                    showColumns={showColumns}
                    onSetColumns={this.onSetColumns}
                  />
                  <Button
                    type="primary"
                    style={{ margin: "0 10px" }}
                    // htmlType="submit"
                    onClick={() => this.handleSubmit()}
                  >
                    搜索
                  </Button>
                  <Button onClick={() => this.onReset()}>重置</Button>
                </Col>
              </Row>
            </Form>
          </div>
          <Table
            style={{ background: "#fff" }}
            rowKey={record => record.handleLogId}
            scroll={messageList.length === 0 ? { x: false } : { x: 1500 }}
            columns={showColumns}
            dataSource={messageList}
            size="middle"
            // rowSelection={rowSelection}
            onChange={(e, filters, sorter) =>
              this.handleTableChange(e, filters, sorter)
            }
            locale={{ emptyText: "暂无数据！" }}
            loading={loading}
            pagination={{
              defaultPageSize: 10,
              showQuickJumper: true,
              showSizeChanger: true,
              current: pageNum,
              total: totalCount,
              showTotal: total => `共有 ${total} 条`
            }}
          />
        </div>
        <Modal
          title="接收人列表"
          visible={this.state.recieverUserVisible}
          onCancel={() => this.setState({ recieverUserVisible: false })}
          footer={[
            <Button
              key="back"
              onClick={() => this.setState({ recieverUserVisible: false })}
            >
              取消
            </Button>
          ]}
        >
          <Table
            style={{ background: "#fff" }}
            rowKey={record => record.msgId}
            columns={userColumn}
            dataSource={listOfRecieverUser}
            size="middle"
            locale={{ emptyText: "暂无数据！" }}
            pagination={{
              defaultPageSize: 10,
              showQuickJumper: true,
              showSizeChanger: true,
              showTotal: total => `共有 ${total} 条`
            }}
          />
        </Modal>
        <Modal
          title="消息内容"
          visible={this.state.messageVisible}
          onCancel={() => this.setState({ messageVisible: false })}
          footer={[
            <Button
              key="back"
              onClick={() => this.setState({ messageVisible: false })}
            >
              取消
            </Button>
          ]}
        >
          {msgContent}
        </Modal>
        <Modal
          title="发送日志"
          visible={this.state.logVisible}
          onCancel={() => this.setState({ logVisible: false })}
          footer={[
            <Button
              key="back"
              onClick={() => this.setState({ logVisible: false })}
            >
              取消
            </Button>
          ]}
        >
          发送日志
        </Modal>
      </div>
    );
  }
}

export default MessagePage;
